/**

 @Name：layuiAdmin 公共业务
 自定义扩展
 权限验证
 @License：LPPL
    
 */

layui.define(function (exports) {
    var $ = layui.$,
        layer = layui.layer,
        laytpl = layui.laytpl,
        setter = layui.setter,
        view = layui.view,
        admin = layui.admin

    layui.$.fn.extend({
        SetFormData: function (data) { // 设置表单数据
            var $this = $(this);
            for (var name in data) {
                var value = data[name];
                var $obj = $this.find('[name = "' + name + '"]');
                var type = $obj.attr('type');
                switch (type) {
                    case "checkbox":
                        if (typeof value == 'boolean') {
                            $obj[0].checked = value;
                        }
                        //   if(!$obj.is(":checked")) {
                        //     $obj.trigger('click');
                        //   }
                        break;
                    case "select":
                        $obj.val(value);
                        break;
                    case "radio":
                        $obj = $this.find('[name="' + name + '"][value="' + value + '"]').prop('checked', 'checked');
                        break;
                    default:
                        $obj.val(value);
                        break;
                }
            }
        },
        SetSelect: function (options) {
            var $this = $(this);
            var defaultOptions = {
                id: 'cItemValue',
                text: 'cItemName',
                description: "==请选择==",
                defaultvalue: "",
                async: true
            };
            var option = $.extend(defaultOptions, options);
            admin.req({
                url: option.url,
                type: 'get',
                async: option.async,
                success: function (res) {
                    if (res.code == 200) {
                        $this.empty();
                        $this.append(new Option(option.description, option.defaultvalue));
                        $.each(res.data, function (index, item) {
                            $this.append(new Option(item[option.text], item[option.id]));
                        });
                        option.success(res);
                    }
                }
            })
        },
        GetFormData: function () {
            var $this = $(this);
            var data = {};
            var t = $this.find('[name]').serializeArray();
            $.each(t, function () {
                data[this.name] = this.value;
            });
            return data;
        },
    });

    layui.$.OpenTab = function (options) {
        if (options.type == 2) {
            options.content += (options.content.indexOf("?") > -1 ? "&v=" : "?v=") + top.layui.setter.version;
            //两秒才允许点一次确定
            var yes = options.yes;
            delete options.yes;
            options.yes = function (index, layero, that) {
                layero.find('a.layui-layer-btn0').css("pointer-events", "none");
                setTimeout(() => {
                    layero.find('a.layui-layer-btn0').css("pointer-events", "")
                }, 2000)
                if (yes) yes(index, layero, that);

                layero.find('iframe').contents().find('#form-submit').trigger('click')
            };
        }
        layer.open(options);
    }
    layui.$.DowloadFile = function (url) {
        var index = url.lastIndexOf("\\");
        if (index == -1) {
            index = url.lastIndexOf("/");
        }
        var strFileName = url.substring(index + 1);
        //判断是否直接为文件路径
        var isPath = url.indexOf('.') > -1;
        if (isPath) {
            view.down({ data: { url: url } });
        }
        //文件接口
        // fetch(url, { mode: 'no-cors' }).then(async res => res.blob().then(blob => {
        //   var a = document.createElement('a');
        //   a.href = window.URL.createObjectURL(blob);
        //   a.download = strFileName;
        //   a.click();
        //   window.URL.revokeObjectURL(url);
        // }))
    }
    //获取的url包括应用程序名
    layui.$.GetPathUri = () => top.location.origin + top.location.pathname.substring(0, top.location.pathname.indexOf('index.html'));
    layui.$.getParam = function (key) {
        let url = location.href.split("?")[1];
        const urlSearchParams = new URLSearchParams(url);
        const params = Object.fromEntries(urlSearchParams.entries());
        var paramValue = params[key];
        if (paramValue == "undefined" || paramValue == null) {
            paramValue = "";
        }
        return paramValue;
    }

    //获取当前页面的用户
    layui.$.getUser = function () {
        let moduleId = window.frameElement?.dataset?.moduleid;
        let data = layui.sessionData(setter.tableName)["UserInfo"].user;
        return data;
    }
    //获取当前页面的权限
    layui.$.getModuleAuths = function () {
        let moduleId = window.frameElement?.dataset?.moduleid;
        let data = layui.sessionData(setter.tableName)["UserInfo"].buttons[moduleId];
        return data;
    }

    //工具栏权限按钮
    layui.$.getToolButtons = function (all_buttons, mId) {
        let moduleId = window.frameElement?.dataset?.moduleid;
        if (mId) {
            moduleId = mId;
        }
        var userinfo = layui.sessionData(setter.tableName)["UserInfo"];
        var buttons = userinfo.buttons[moduleId]?.filter(t => t.cPosition == 1);
        let html = [];
        buttons?.forEach(function (item) {
            if (all_buttons && !all_buttons.includes(item.cEnCode)) {
                return;
            }
            let i_html = '';
            if (item.cIcon.startsWith("fa")) {
                i_html = '<i class="fa ' + item.cIcon + ' fa-fw" aria-hidden="true"></i>';
            } else {
                i_html = '<i class="layui-icon ' + item.cIcon + '"></i>';
            }
            html.push(`<button class="layui-btn layui-btn-sm" lay-active="${item.cEnCode}">${i_html}${item.cTitle}</button>`);
        })
        if (html.length > 0) {
            html.unshift('<div>');
            html.push('</div>');
        }
        return html.join('');
    }
    //获取行权限按钮
    layui.$.getRowButtons = function (all_buttons, trigger_type, mId) {
        let moduleId = window.frameElement?.dataset?.moduleid;
        if (mId) {
            moduleId = mId;
        }
        var userinfo = layui.sessionData(setter.tableName)["UserInfo"];
        var buttons = userinfo.buttons[moduleId]?.filter(t => t.cPosition == 2);
        let html = [];
        trigger_type = trigger_type || 'lay-active';

        buttons?.forEach(function (item) {
            if (all_buttons && !all_buttons.includes(item.cEnCode)) {
                return;
            }
            let i_html = '';
            if (item.cIcon) {
                if (item.cIcon.startsWith("fa")) {
                    i_html = '<i class="fa ' + item.cIcon + ' fa-fw" aria-hidden="true"></i>';
                } else {
                    i_html = '<i class="layui-icon ' + item.cIcon + '"></i>';
                }
            }
            let color = '';
            if (item.cEnCode.includes('delete')) {
                color = 'layui-bg-red';
            } else if (item.cEnCode.includes('edit')) {
                color = 'layui-bg-blue';
            } else if (item.cEnCode.includes('reset')) {
                color = 'layui-btn-warm';
            }
            html.push(`<button class="layui-btn ${color} layui-btn-xs" ${trigger_type}="${item.cEnCode}">${i_html}${item.cTitle}</button>`);
        })
        if (html.length > 0) {
            html.unshift(`<div>`);
            html.push(`</div>`);
        }
        return html.join(``);
    }

    layui.$.TableSet = function (table, tableName) {
        var elements = $('[lay-id="' + tableName + '"] .layui-table-tool');
        var batch_button = elements.find('button[lay-active="x-batch-delete"]');
        batch_button?.addClass("layui-btn-disabled");
        batch_button?.attr('disabled', 'disabled');
        // 复选框事件 批量删除
        table.on('checkbox(' + tableName + ')', function (obj) {
            $(obj.tr).first().click();
            var checkData = table.checkStatus(tableName).data;

            if (batch_button.length !== 0) {
                if (checkData.length > 0) {
                    batch_button.removeClass("layui-btn-disabled");
                    batch_button.removeAttr('disabled');
                } else {
                    batch_button.addClass("layui-btn-disabled");
                    batch_button.attr('disabled', 'disabled');
                }
            }
        });
    }

    $(document).on('click', '.layui-dropdown div a', function () {
        layui.dropdown.close(layui.dropdown.index);
    });
    //公共业务的逻辑处理可以写在此处，切换任何页面都会执行
    //……
    //退出
    admin.events.logout = function () {
        //执行退出接口
        admin.req({
            url: '/api/Login/Logout',
            type: 'post',
            success: function (res) { //这里要说明一下：done 是只有 response 的 code 正常才会执行。而 success 则是只要 http 为 200 就会执行
                //清空本地记录的 token，并跳转到登入页
                admin.exit(function () {
                    //location.href = 'user/login.html';
                });
            }
        });
    };
    //重置表单搜索框
    admin.events.reset = function () {
        $(this).parents(".layui-form").find('input')
            .not(':button, :submit, :reset, :hidden')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        $(this).parents(".layui-form").find('.layui-form-select').find('dl').find('dd[lay-value=0]').click();
        $(this).parents(".layui-form").find('.layui-form-select').find('dl').find('dd[lay-value=""]').click();
    }

    var common = {
        checkPermissions: function () {
            //权限按钮显示隐藏
            let moduleId = window.frameElement?.dataset?.moduleid;
            var $element = $("#x-operation");
            if (moduleId && $($element).length != 0) {
                $element.find("button").attr('authorize', 'no');
                var userinfo = layui.sessionData(setter.tableName)["UserInfo"];
                var buttons = userinfo.buttons[moduleId];
                if (buttons != undefined) {
                    $.each(buttons, function (i) {
                        $element.find("#" + buttons[i].cEnCode).attr('authorize', 'yes');
                    });
                }
                $element.find("button[authorize=no]").remove();
                $element.show();
            }
        }
    };
    //common.checkPermissions();

    //对外暴露的接口
    exports('common', common);
});